//
//  PKTestTableView.m
//  ParentsCommunity
//
//  Created by tianlong on 2018/4/28.
//  Copyright © 2018年 XES. All rights reserved.
//

#import "PKTestTableView.h"
#import "Masonry.h"

@interface PKTestTableView ()<UITableViewDelegate,UITableViewDataSource>
@property (strong, nonatomic) NSMutableArray *dataM;
@end

@implementation PKTestTableView

static NSString *cellId = @"PKTestTableView";

- (instancetype)initWithDataSource:(NSArray *)dataSource{
    self = [super init];
    if (self) {
        self.dataM = [NSMutableArray arrayWithArray:dataSource];
        
        if (!_tableView) {
            UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain] ;
            tableView.delegate = self;
            tableView.dataSource = self;
            [self addSubview:tableView];
            self.tableView = tableView;
        }

    }
    return self;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    self.tableView.frame = self.bounds;
}

- (void)insertTestModel:(PKTestModel *)model {
    [self.dataM addObjectSafe:model];
    [self.tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataM.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    PKTestModel *model =nil;
    if (indexPath.row < self.dataM.count) {
        model = self.dataM[indexPath.row];
        cell.textLabel.text = model.title;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    PKTestModel *model =nil;
    if (indexPath.row < self.dataM.count) {
        model = self.dataM[indexPath.row];
        if ([model.target respondsToSelector:model.action]) {
            
            if (IS_IOS_10_LATER) {
                SEL selector = model.action;
                IMP imp = [model.target methodForSelector:selector];
                void (*func)(id, SEL) = (void *)imp;
                func(model.target, selector);
            }
//            else {
//                [model.target performSelector:model.action withObject:nil];
//            }
        }
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}


@end



@implementation PKTestModel
- (instancetype)initWithTitle:(NSString *)title action:(SEL)action target:(id)target{
    self = [super init];
    if (self) {
        self.title = title;
        self.action = action;
        self.target = target;
    }
    return self;
}

@end

